package com.icinfo.cloud.provider.common.config;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.icinfo.cloud.common.core.config.CfRedisRepository;
import com.icinfo.cloud.xzcf.provider.member.permission.dto.PermissionTree;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.lang.reflect.Modifier;
import java.util.List;

@Configuration
public class RedisUtil {
    @Resource
    private CfRedisRepository cfRedisRepository;
    /**
     * 菜单信息缓存前缀
     */
    public static final String REDIS_PREFIX_PERMISSIONTREE = "user-permissionTree:";
    public static final String REDIS_PREFIX_ZLB = "zlbPhone";

    /**
     *判断key是否存在
     * @author liyafeng
     * @date 2022/7/26
     * @param username
     * @return {@link boolean}
     */
    public boolean existsPermissionKey(String orgCode,String username) {
        String key = REDIS_PREFIX_PERMISSIONTREE +orgCode+ username;
        return cfRedisRepository.exists(key);
    }
    /**
     *获取权限信息
     * @author liyafeng
     * @date 2022/7/26
     * @param username
     * @return {@link String}
     */
    public String getPermission(String deptCode,String username) {
        String key = REDIS_PREFIX_PERMISSIONTREE +deptCode+ username;
        return cfRedisRepository.get(key);
    }
    public void delRedis(String orgCode, String userName) {
        String key = REDIS_PREFIX_PERMISSIONTREE +orgCode+ userName;
        cfRedisRepository.del(key);
    }
    /**
     * 添加菜单权限redis
     * @author liyafeng
     * @date 2022/7/26
     * @param permissionTrees
     * @return
     */
    public void putPermissionTrees(String orgCode,String username, List<PermissionTree> permissionTrees) {
        // key=当前用户归属机构ID:user-details:loginName
        //String key = userDetails.getInTenantId() + ":" + REDIS_PREFIX_USER + userDetails.getUsername()+":"+userDeviceId;
        String key = REDIS_PREFIX_PERMISSIONTREE + orgCode+username;
        Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create();
        cfRedisRepository.setExpire(key, gson.toJson(permissionTrees), 30*60*1000);
    }
}
